package com.itheima;

import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.*;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;

/*
 * 配置映射
 *
 * 查看映射
 * */
@RunWith(SpringRunner.class)
@SpringBootTest
public class Demo02PutMapping {

    //注入高级客户端对象，用来操作es
    @Autowired
    private RestHighLevelClient client;


    /**
     * 映射操作：
     * 1.配置映射，一共2种方式：
     *   第一种：使用XContentBuilder,构建请求体
     *   第二种：使用JSON字符串
     * 2.查看映射配置
     */
    @Test
    public void createIndex() throws IOException {
        //创建请求对象：配置映射
        PutMappingRequest request = new PutMappingRequest("heima");
        //设置请求体，source("请求体json字符串"，"请求体的数据类型");
        request.source("{\"properties\":{\"title\":{\"type\":\"text\"," +
                "\"analyzer\":\"ik_max_word\"},\"subtitle\":{\"type\":\"text\",\"analyzer" +
                "\":\"ik_max_word\"},\"category\":{\"type\":\"keyword\"},\"brand\":{\"type" +
                "\":\"keyword\"},\"price\":{\"type\":\"float\"},\"images\":{\"type\":" +
                "\"keyword\",\"index\":false}}}", XContentType.JSON);
        //2.客户端发送请求，获取响应对象
        AcknowledgedResponse response = client.indices().putMapping(request, RequestOptions.DEFAULT);
        //3.打印响应结果
        System.out.println("acknowledged::"+response.isAcknowledged());
    }

    /**
     * 查看映射
     * 1.创建请求对象：查看映射
     *    设置索引库name
     * 2.客户端发送请求，获取响应对象
     * 3.打印响应结果
     */
    @Test
    public void getMapping() throws IOException {
        //1.创建请求对象：查看映射
        GetMappingsRequest request = new GetMappingsRequest();
        //设置索引库name
        request.indices("heima");
        //2.客户端发送请求，获取响应对象
        GetMappingsResponse response = client.indices().getMapping(request, RequestOptions.DEFAULT);
        //3.打印响应结果
        System.out.println("mappings::"+response.mappings());
        System.out.println("Source::"+response.mappings().get("heima").getSourceAsMap());
    }
}
